﻿using System.Web;
using System.Web.Routing;

namespace Ornament.Web.Mvc
{
    public class JavaScriptHandler : IRouteHandler
    {
        #region IRouteHandler Members

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new ZIPJavascript(requestContext);
        }

        #endregion
    }

    public class ZIPJavascript : IHttpHandler
    {
        public ZIPJavascript(RequestContext requestContext)
        {
            ProcessRequest(requestContext);
        }

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
        }

        #endregion

        public static void ProcessRequest(RequestContext requestContext)
        {
            HttpResponseBase response = requestContext.HttpContext.Response;
            HttpServerUtilityBase server = requestContext.HttpContext.Server;
            string validRequestFile = requestContext.RouteData.Values["filename"].ToString().ToLower();

            //response.Clear();
            if (validRequestFile.EndsWith("js"))
            {
                response.ContentType = "application/x-javascript";
                //response.ContentEncoding = "gzip";
                response.AppendHeader("Content-Encoding", "gzip");
                string path = server.MapPath("~/Scripts/" + validRequestFile + ".gz");
                response.TransmitFile(path);
            }
            response.End();
        }
    }
}